<style lang="scss" scoped>
  @import '@/assets/css/variable';
  .applyActivity{
    position: absolute;
    top: 0;
    bottom: 0;
    width: 100%;
    background-color: $main-bgc;
    min-height: 100%;
    font-size: 1.2rem;
    overflow: auto;
    box-sizing: border-box;
    .title-box{
      padding: 1.8rem 1.6rem;
      display: flex;
      .left-line{
        flex: 0 0 0.3rem;
      }
      .title{
        padding-left: 0.5rem;
        font-size: 1.5rem;
        padding-bottom: 0 !important;
      }
    }
    .base-info{
      background-color: white;
      width: 100%;
      box-sizing: border-box;
      .field-box{
        width: 100%;
        padding: 1.4rem 1.6rem;
        position: relative;
        box-sizing: border-box;
        &:after {
          position: absolute;
          box-sizing: border-box;
          content: ' ';
          pointer-events: none;
          right: 16px;
          bottom: 0;
          left: 16px;
          border-bottom: 1px solid #ebedf0;
          -webkit-transform: scaleY(.5);
          transform: scaleY(.5);
        }
        .label{
          position: relative;
          font-size: 1.4rem;
          color: #646566;
          padding-bottom: 1.2rem;
          &:after {
            content: '*';
            color: red;
            position: absolute;
            left: -0.8rem;
          }
        }
        .my-img{
          width: 100%;
          box-sizing: border-box;
          position: relative;
          box-sizing: border-box;
          img{
            width: 100%;
            object-fit: fill;
          }
          .change-pic{
            position: absolute;
            width: 100%;
            height: 2.8rem;
            right: 0rem;
            bottom: 0.1rem;
            display: flex;
            align-items: center;
            justify-content: center;
            background-color: rgba($color: #000000, $alpha: 0.7);
            color: white;
            font-size: 1.2rem;
            box-sizing: border-box;
          }
        }
      }
    }
    .introduce{
      background-color: white;
      .introduce-title{
        font-size: 1.4rem;
      }
      .btnAddSomeBox{
        display: flex;
        align-items: center;
        justify-content: space-between;
        .addSome{
          flex: 1;
        }
        .interval{
          flex: 0 0 1rem;
        }
      }
    }
    .fix-bottom{
      position: fixed;
      bottom: 1rem;
      left: 0;
      right: 0;
      width: 100%;
      z-index: 3;
      box-sizing: border-box;
    }
  }
  .van-button__text{
    font-size: 1.4rem !important;
  }
  .van-field__error-message{
    text-align: right !important;
  }
</style>
<template>
  <div class="applyActivity">
    <div class="title-box">
      <span class="left-line" :style="{backgroundColor: $store.getters.getMainColor}"></span>
      <span class="title">报名模板</span>
    </div>
    <div class="base-info padding-lr">
      <van-form>
        <!-- 通过 pattern 进行正则校验 -->
        <van-field
          required
          v-model="form.title"
          label="活动名称"
          placeholder="请填写活动名称"
          input-align="right"
        />
        <div class="field-box">
          <div class="label">活动封面 <span class="tip fs-12 color-s">建议上传比例为4:3的图片</span></div>
          <!-- <van-uploader v-model="form.cover" max-count="1" :before-read="beforeRead" :after-read="afterRead" :max-size="1000 * 1024" @oversize="onOversize"/> -->
          <div class="my-img">
            <!-- <img :src="form.cover" alt=""> -->
            <van-image :src="form.cover" fit="scale-down"/>
            <span class="change-pic" @click="changePic">更换图片</span>
            <input
              type="file"
              class="file-input d-none"
              ref="fileInput"
              @change="handleFileChange"
            >
          </div>
        </div>
        <van-cell title="活动截止时间" is-link :value="form.endDate" @click="show = true" />
        <!-- <van-calendar v-model:show="show" @confirm="onConfirm" /> -->
      </van-form>
    </div>
    <div class="introduce padding-all-l margT-l">
      <h2 class="introduce-title">活动介绍</h2>
      <div v-for="(item,index) in form.introduce" :key="Number(item.id)">
        <my-text v-if="item.type === 'text'" class="margT-l" :editorHtml="item.value" :id="Number(item.id)" :index="index"
          @editorHtmlChange="editorHtmlChange"
          @deleteIntroduceItem="deleteIntroduceItem"
          @downIntroduceItem="downIntroduceItem"
          @upIntroduceItem="upIntroduceItem">
        </my-text>
        <my-img v-if="item.type === 'img'" class="margT-l" :value="item.value" :id="Number(item.id)" :index="index"
          @ChangeFile="ChangeFile"
          @deleteIntroduceItem="deleteIntroduceItem"
          @downIntroduceItem="downIntroduceItem"
          @upIntroduceItem="upIntroduceItem">
        </my-img>
      </div>
      <div class="btnAddSomeBox margT-l">
        <div class="addSome">
          <van-button size="small" type="default" block @click="addTextBtn">添加文本{{textNum}}/10</van-button>
        </div>
        <div class="interval"></div>
        <div class="addSome">
          <van-button size="small" type="default" block @click="addPicBtn">添加图片{{imgNum}}/10</van-button>
          <input
              type="file"
              class="file-input d-none"
              ref="addPicInput"
              @change="addPicInputChange"
            >
        </div>
      </div>
    </div>
    <div class="introduce padding-all-l margT-l">
      <h2 class="introduce-title">报名表单</h2>
      <div class="color-s margT-s">报名表单可在后台管理系统中自定义</div>
      <div class="margT-l" v-if="form.create_form">
        <k-form-build ref="kfb" :value="form.create_form" />
      </div>
      <!-- <button @click="handleGetData">获取数据</button> -->
    </div>  
    <div class="tabbar-height"></div>
    <van-popup v-model="show" position="bottom">
      <van-datetime-picker
        v-model="endDate"
        type="datetime"
        title="选择完整时间"
        :min-date="minDate"
        :max-date="maxDate"
        @confirm="endTimeConfirm"
      />
    </van-popup>
    <div class="fix-bottom padding-lr">
      <van-button :color="$store.getters.getMasterColor" block @click="submit">{{is_edit==0?"创建活动":"保存修改"}}</van-button>
    </div>
  </div>
</template>

<script>
// @ is an alias to /src
import { Toast,Form,Field,Button,Uploader,Cell, Popup, Calendar, DatetimePicker } from 'vant';
import { Image as VanImage } from 'vant';
import MyText from '@/components/MyText';
import MyImg from '@/components/MyImg';
import utils from '@/assets/js/utils.js'

// import { quillEditor } from 'vue-quill-editor'
// import 'quill/dist/quill.core.css'
// import 'quill/dist/quill.snow.css'
// import 'quill/dist/quill.bubble.css'

// const formatDate = (date) => `${date.getFullYear()}-${(date.getMonth() + 1)<10?'0'+(date.getMonth() + 1):date.getMonth() + 1}-${(date.getDate())<10?'0'+(date.getDate()):date.getDate()} ${(date.getHours())<10?'0'+(date.getHours()):date.getHours()}:${(date.getMinutes())<10?'0'+(date.getMinutes()):date.getMinutes()}`;
export default {
  name: "ApplyActivity",
  components: {
   [Form.name]: Form,
   [Field.name]: Field,
   [Button.name]: Button,
   [Uploader.name]: Uploader,
   [Cell.name]: Cell,
   [Calendar.name]: Calendar,
   [DatetimePicker.name]: DatetimePicker,
   [Popup.name]: Popup,
   VanImage,
   MyText,
   MyImg
   // quillEditor
  },
  data() {
    return {
      show: false,
      name: "满天星",
      pattern: /\d{6}/,
      endDate: new Date(2020, 0, 1),
      minDate: new Date(2020, 0, 1),
      maxDate: new Date(2028, 10, 1),
      form: {
        title: "",
        cover: "https://vkceyugu.cdn.bspapp.com/VKCEYUGU-f025bed1-101b-4383-9c33-bbbeccec7177/5fc47e7a-e89a-470f-843c-902210a43215.jpg",
        endDate: utils.formatDateYMDHM(new Date(new Date().getTime() + 86400000*7)).toString(),
        introduce: []
      },
      editorOption: {
        placeholder: "请在这里输入内容",
        modules: {
          toolbar:[[{ 'size': ['small', false, 'large', 'huge'] }]]
        }
      },
      textNum: 0,
      imgNum: 0,
      is_edit:0,
      jsonData: {
        list: [
          {
            type: 'input',
            label: '姓名',
            options: {
              width: '100%',
              defaultValue: '',
              placeholder: '请输入姓名',
              disabled: false
            },
            model: 'name',
            key: 'name',
            rules: [{ required: true, message: '必填项' }]
          },
          {
            type: 'input',
            label: '联系方式',
            options: {
              width: '100%',
              defaultValue: '',
              placeholder: '请输入手机号',
              disabled: false
            },
            model: 'mobile',
            key: 'mobile',
            rules: [{ required: true, message: '必填项' }]
          }
        ],
        config: {
          layout: 'horizontal',
          labelCol: { span: 4 },
          wrapperCol: { span: 18 },
          hideRequiredMark: false,
          customStyle: ''
        }
      }
    }
  },
  created() {
  },
  mounted () {
    // this.getTypeNum(this.form.introduce)
    this.getActivityItem()
    this.is_edit = this.$route.query.is_edit
  },
  methods: {
    handleGetData () {
      // 使用getData函数获取数据
      this.$refs.kfb.getData().then(values => {
        console.log('验证通过', values)
      }).catch(() => {
        console.log('验证未通过，获取失败')
      })
    },
    changePic() {
      this.$refs.fileInput.click()
    },
    addPicBtn() {
      this.$refs.addPicInput.click()
    },
    addPicInputChange(e) {
      const _this = this;
      const img = e.target.files[0];
      if (img.type != 'image/jpeg' && img.type != 'image/png') {
        Toast('请上传jpg或png格式的图片');
        return false;
      }
      if(img.size > 3000 * 1024) {
        Toast("图片大小请不要超过3M")
        return
      }
      utils.blobToDataURL(img, (base64Url) => {
        let introduce = this.form.introduce
        introduce.push({
          id: (Number(introduce[introduce.length-1] && introduce[introduce.length-1].id)+1) || 1,
          type:"img",
          value: base64Url
        })
        this.form.introduce = introduce
        this.getTypeNum(this.form.introduce)
      });
    },
    handleFileChange(e) {
      const _this = this;
      const img = e.target.files[0];
      if (img.type != 'image/jpeg' && img.type != 'image/png' && img.type != 'image/gif') {
        Toast('请上传jpg或png格式的图片');
        return false;
      }
      if(img.size > 3000 * 1024) {
        Toast("图片大小请不要超过3M")
        return
      }
      utils.blobToDataURL(img, (base64Url) => {
        _this.form.cover = base64Url
      });
    },
    submit() {
      const form = this.form
      let params = {
        openid: this.$store.state.openid,
        title: form.title,
        cover: form.cover,
        end_time: form.endDate,
        introduce: JSON.stringify(form.introduce),
        create_form: JSON.stringify(form.create_form)
      }
      if(this.is_edit==1) params.id = form.id
      // params.cover = this.cover
      this.$request.activitySave(params).then(res=>{
        console.log("res", res)
        if(res.ret == 200){
          Toast("发布成功")
          this.$router.replace("/manage")
        }
      })
    },
    getActivityItem() {
      let params = {
        id: Number(this.$route.params.id)
      }
      this.$request.getActivityItem(params).then(res=>{
        let data = res.data
        this.form.id = data.id
        this.form.title = data.title
        this.form.cover = data.cover
        this.form.introduce = data.introduce
        this.form.create_form = data.create_form
        this.getTypeNum(this.form.introduce)
      })
    },
    addTextBtn() {
      let introduce = this.form.introduce || []
      introduce.push({
        id: (Number(introduce[introduce.length-1] && introduce[introduce.length-1].id)+1) || 1,
        type:"text",
        value:""
      })
      this.form.introduce = introduce
      this.getTypeNum(this.form.introduce)
    },
    getTypeNum(arr) {
      this.textNum = 0
      this.imgNum = 0
      for(let i = 0; i < arr.length; i++) {
        if(arr[i].type === 'text') {
          this.textNum++
        }else{
          this.imgNum++
        }
      }
    },
    upIntroduceItem(index) {
      console.log("upIntroduceItem", this.index)
      let introduce = this.form.introduce
      console.log("introduce[index - 1]", introduce[index - 1])
      if(introduce[index - 1]){
        const type = introduce[index-1].type
        const value = introduce[index-1].value
        introduce[index-1].type = introduce[index].type;
        introduce[index-1].value = introduce[index].value;
        introduce[index].type = type;
        introduce[index].value = value;
        this.form.introduce = introduce;
      }else{
        Toast("已在最后面")
      }
    },
    downIntroduceItem(index) {
      console.log("downIntroduceItem", this.index)
      let introduce = this.form.introduce
      console.log("introduce[index + 1]", introduce[index + 1])
      if(introduce[index + 1]){
        const type = introduce[index+1].type
        const value = introduce[index+1].value
        introduce[index+1].type = introduce[index].type;
        introduce[index+1].value = introduce[index].value;
        introduce[index].type = type;
        introduce[index].value = value;
        this.form.introduce = introduce;
      }else{
        Toast("已在最前面")
      }
    },
    deleteIntroduceItem(id) {
      let introduce = this.form.introduce
      this.form.introduce = introduce.filter(item => {
        return item.id != id
      })
      this.getTypeNum(this.form.introduce)
      // introduce.splice(index,1)
      // this.form.introduce = introduce
    },
    onEditorChange(value) {
      console.log(value);
    },
    ChangeFile(item) {
      let introduce = this.form.introduce
      let newIntroduce = introduce.map((i) => {
        if(i.id == item.id) {
          i.value = item.value
        }
         return i
      })
      this.form.introduce = newIntroduce
    },
    editorHtmlChange(item) {
      let introduce = this.form.introduce
      let newIntroduce = introduce.map((i) => {
        if(i.id == item.id) {
          i.value = item.value
        }
        return i
      })
      this.form.introduce = newIntroduce
    },
    endTimeConfirm(value) {
      this.show = false;
      this.form.endDate = utils.formatDateYMDHM(value);
    },
    onOversize(file) {
      console.log('file', file);
      console.log('文件大小不能超过 1M');
    },
    afterRead(value) {
      console.log("file.value", value);
      // this.form.cover = value.content
    },
    beforeRead(file) {
      if (file.type != 'image/jpeg' && file.type != 'image/png') {
        Toast('请上传jpg或png格式的图片');
        return false;
      }
      return true;
    },
  }
};
</script>
